package com.nice.message;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class Message {

	public static final byte LOGIN = 2;
	public int len;
	public byte type;
	public int to;
	public int from;
	public byte[] body=new byte[0];
	//id字段不序列号,仅保存在服务端
	public MessageHandler sender;
	public long id = System.currentTimeMillis();
	
	public ByteBuf toByte() {
		ByteBuf buf = Unpooled.buffer(len + 13);
		buf.writeByte(type);
		buf.writeInt(len);
		buf.writeInt(from);
		buf.writeInt(to);
		buf.writeBytes(body);
		return buf;
	}

	// type|len|form|to|body
	public static Message from(String data) {
		Message msg = new Message();
		String type = data.substring(0, 1);
		String len = data.substring(1, 5);
		String from = data.substring(5, 9);
		String to = data.substring(9, 13);

		msg.type = Byte.valueOf(type);
		msg.len = Integer.valueOf(len);
		msg.from = Integer.valueOf(from);
		msg.to = Integer.valueOf(to);
		msg.body = data.substring(13).getBytes();
		return msg;
	}

	public static Message from(byte[] allData) {
		int len = allData.length;
		ByteBuf buf = Unpooled.wrappedBuffer(allData);
		byte[] body = new byte[len - 13];
		Message msg = new Message();
		msg.type = buf.readByte();
		msg.len = buf.readInt();
		msg.from = buf.readInt();
		msg.to = buf.readInt();
		buf.readBytes(body);
		msg.body = body;
		return msg;
	}

	public static Message from(byte[] body, byte type, int from, int to) {
		Message msg = new Message();
		msg.type = type;
		msg.len = body.length;
		msg.to = to;
		msg.from = from;
		msg.body = body;
		return msg;
	}

	public static Message from(byte[] data, int offset, int len) {
		ByteBuf buf = Unpooled.wrappedBuffer(data, offset, len);
		byte[] body = new byte[len - 13];
		Message msg = new Message();
		msg.type = buf.readByte();
		msg.len = buf.readInt();
		msg.from = buf.readInt();
		msg.to = buf.readInt();
		buf.readBytes(body);
		msg.body = body;
		return msg;
	}

	@Override
	public String toString() {
		return "Message [to=" + to + ", from=" + from + ", body="
				+ new String(body) + "]";
	}

}
